﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using SportStore.DomainModel.Abstract;
using SportStore.DomainModel.Entities;
using  System.Data.Linq;
using System.Data.Entity;

namespace SportStore.DomainModel.Concrete
{
    public class SqlProductsRepository : IProductsRepository
    {
        private Table<Product> productTable;

        /// <summary>
        /// Initializes a new instance of the <see cref="SqlProductsRepository"/> class.
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        public SqlProductsRepository(string connectionString)
        {
            productTable = (new DataContext(connectionString)).GetTable<Product>();
        }

        /// <summary>
        /// Gets the products.
        /// </summary>
        public  IQueryable<Product> Products
        {
            get { return productTable; }
        }

        /// <summary>
        /// Saves the product.
        /// </summary>
        /// <param name="product">The product.</param>
        public void SaveProduct(Product product)
        {
            EnsureValid(product, "Name", "Description", "Category", "Price");
            if (product.ProductID == 0)
                productTable.InsertOnSubmit(product);
            else
            {
                productTable.Attach(product);
                productTable.Context.Refresh(RefreshMode.KeepCurrentValues, product);
            }

            productTable.Context.SubmitChanges();
        }
        private void EnsureValid(IDataErrorInfo validatable, params string [] properties)
        {
            if (properties.Any(x=>validatable[x] != null)) throw new InvalidOperationException("The object is invalid.");
        }

        public void DeleteProduct(Product product)
        {
            productTable.DeleteOnSubmit(product);
            productTable.Context.SubmitChanges();
        }
    }
}
